﻿using System.Collections.Generic;
using System.Xml;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Core.Persistence.Models;
using Jayden.Dll.Core.Persistence.Xml;

namespace Jayden.Dll.Core.Membership
{
	public class XmlRoleDataAccess : XmlDataAccess<Role>, RoleDataAccess
	{
		public XmlRoleDataAccess(Configuration config, UnitOfWork uow, Entity entity) : base(config, uow, entity) { }

		public List<Role> FindAll(int page, int pageSize, out int totalRecords)
		{
			List<Role> roles = new List<Role>();
			using (XmlNodeProxy root = GetRoot(false))
			{
				foreach (XmlNode node in root.Node.ChildNodes)
					if (node is XmlElement && node.Name == Entity.Table.TableName)
						roles.Add(CreateFromXmlElement(node as XmlElement));
			}
			totalRecords = roles.Count;
			return roles;
		}

		private string m_XPathRoleName = null;
		protected string XPathRoleName(string rolename)
		{
			if (m_XPathRoleName == null)
				m_XPathRoleName = XmlHelper.XPath(Entity, Entity["RoleName"]);
			return string.Format(m_XPathRoleName, rolename);
		}

		public void DeleteByName(string roleName)
		{
			string xpath = XPathRoleName(roleName);
			using (XmlNodeProxy root = GetRoot(true))
			{
				XmlNode node = root.Node.SelectSingleNode(xpath);
				if (node == null)
					return;
				node.ParentNode.RemoveChild(node);
			}
		}
	}
}
